import { Router, Request, Response } from 'express';
import { asyncHandler } from '../utils/asyncHandler';
import { createError } from '../middleware/errorHandler';
import { AuthService } from '../services/AuthService';
import { authenticate } from '../middleware/auth';
import { isGoogleConfigured } from '../config/google';
import { isGitHubConfigured } from '../config/github';

const router: Router = Router();
const authService = new AuthService();

// 接口定义
interface LoginRequest {
  email: string;
  password: string;
}

interface RegisterRequest {
  username?: string;
  email: string;
  password: string;
  firstName?: string;
  lastName?: string;
}

interface GoogleAuthRequest {
  code: string; // Google authorization code
}

interface GitHubAuthRequest {
  code: string; // GitHub authorization code
}

interface RefreshTokenRequest {
  refreshToken: string;
}

interface ChangePasswordRequest {
  oldPassword: string;
  newPassword: string;
}

// POST /api/v1/auth/register - 用户注册
router.post('/register', asyncHandler(async (req: Request, res: Response) => {
  const { username, email, password, firstName, lastName }: RegisterRequest = req.body;
  
  if (!email || !password) {
    throw createError('邮箱和密码是必需的', 400);
  }
  
  if (password.length < 6) {
    throw createError('密码长度至少6位', 400);
  }

  try {
    const result = await authService.register({
      username,
      email,
      password,
      firstName,
      lastName,
    });

    res.status(201).json({
      success: true,
      data: result,
      message: '注册成功',
    });
  } catch (error: any) {
    throw createError(error.message, 400);
  }
}));

// POST /api/v1/auth/login - 用户登录
router.post('/login', asyncHandler(async (req: Request, res: Response) => {
  const { email, password }: LoginRequest = req.body;
  
  if (!email || !password) {
    throw createError('邮箱和密码是必需的', 400);
  }

  try {
    const result = await authService.login(email, password);

    res.json({
      success: true,
      data: result,
      message: '登录成功',
    });
  } catch (error: any) {
    throw createError(error.message, 401);
  }
}));

// POST /api/v1/auth/google - Google OAuth登录
router.post('/google', asyncHandler(async (req: Request, res: Response) => {
  const { code }: GoogleAuthRequest = req.body;
  
  if (!code) {
    throw createError('Google授权码是必需的', 400);
  }

  if (!isGoogleConfigured()) {
    throw createError('Google OAuth未配置', 500);
  }

  try {
    const result = await authService.googleLogin(code);

    res.json({
      success: true,
      data: result,
      message: 'Google登录成功',
    });
  } catch (error: any) {
    throw createError(error.message, 401);
  }
}));

// POST /api/v1/auth/github - GitHub OAuth登录
router.post('/github', asyncHandler(async (req: Request, res: Response) => {
  const { code }: GitHubAuthRequest = req.body;
  
  if (!code) {
    throw createError('GitHub授权码是必需的', 400);
  }

  if (!isGitHubConfigured()) {
    throw createError('GitHub OAuth未配置', 500);
  }

  try {
    const result = await authService.githubLogin(code);

    res.json({
      success: true,
      data: result,
      message: 'GitHub登录成功',
    });
  } catch (error: any) {
    throw createError(error.message, 401);
  }
}));

// POST /api/v1/auth/refresh - 刷新token
router.post('/refresh', asyncHandler(async (req: Request, res: Response) => {
  const { refreshToken }: RefreshTokenRequest = req.body;
  
  if (!refreshToken) {
    throw createError('刷新令牌是必需的', 400);
  }

  try {
    const result = await authService.refreshToken(refreshToken);

    res.json({
      success: true,
      data: result,
      message: '令牌刷新成功',
    });
  } catch (error: any) {
    throw createError(error.message, 401);
  }
}));

// GET /api/v1/auth/me - 获取当前用户信息
router.get('/me', authenticate, asyncHandler(async (req: Request, res: Response) => {
  try {
    const user = await authService.getCurrentUser(req.user!.id);

    res.json({
      success: true,
      data: user,
      message: '获取用户信息成功',
    });
  } catch (error: any) {
    throw createError(error.message, 404);
  }
}));

// POST /api/v1/auth/change-password - 修改密码
router.post('/change-password', authenticate, asyncHandler(async (req: Request, res: Response) => {
  const { oldPassword, newPassword }: ChangePasswordRequest = req.body;
  
  if (!oldPassword || !newPassword) {
    throw createError('原密码和新密码是必需的', 400);
  }

  if (newPassword.length < 6) {
    throw createError('新密码长度至少6位', 400);
  }

  try {
    await authService.changePassword(req.user!.id, oldPassword, newPassword);

    res.json({
      success: true,
      message: '密码修改成功',
    });
  } catch (error: any) {
    throw createError(error.message, 400);
  }
}));

// POST /api/v1/auth/logout - 用户登出
router.post('/logout', asyncHandler(async (req: Request, res: Response) => {
  // 在真实应用中，你可能想要将token加入黑名单
  // 这里简化处理，客户端需要删除本地存储的token
  res.json({
    success: true,
    message: '登出成功',
  });
}));

// GET /api/v1/auth/config - 获取认证配置信息
router.get('/config', asyncHandler(async (req: Request, res: Response) => {
  res.json({
    success: true,
    data: {
      googleEnabled: isGoogleConfigured(),
      googleClientId: process.env.GOOGLE_CLIENT_ID || null,
    },
    message: '获取配置成功',
  });
}));

export default router;